package com.hyd.hx_adr.modules.common.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.hyd.hx_adr.annotations.PassToken;
import com.hyd.hx_adr.domain.entity.JsonResult;
import com.hyd.hx_adr.modules.common.domain.info.SmsCodeInfo;
import com.hyd.hx_adr.modules.common.service.CommonService;
import com.hyd.hx_adr.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private CommonService commonService;

    @Autowired
    private RedisUtils redisUtils;

    @PostMapping("/getSmsCode")
    public JsonResult<String> getSmsCode(@RequestBody SmsCodeInfo info) {
        return commonService.getSmsCode(info);
    }

    @PostMapping("/getVerifyCode")
    @PassToken
    public void verifyCode(HttpServletRequest request, HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100,30,4,25);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try{
            lineCaptcha.write(response.getOutputStream());
            String code = lineCaptcha.getCode();
            String codeId = UUID.randomUUID().toString();
            // 5分钟有效
            redisUtils.set(codeId + "_VERIFY_CODE", code, 60 * 5);
            response.setHeader("codeId", codeId);
            response.setHeader("code",code);
            request.getSession().setAttribute("piccode",code);
            response.getOutputStream().close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
